package com.lib.torment.androidlib.net;

import android.util.Log;

import com.lib.torment.androidlib.net.interceptor.HttpLoggingInterceptor;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Retrofit配置类
 * Created by Torment on 2016/9/5.
 */
public abstract class RetrofitManager {
    private static final String TAG = "RetrofitUtils";

    private Retrofit mRetrofit;
    private OkHttpClient mOkHttpClient;

    protected Retrofit createRetrofit(String baseUrl) {
        return getRetrofit(baseUrl);
    }

    /**
     * 创建Retrofit对象
     *
     * @return
     */
    public Retrofit getRetrofit(String baseUrl) {
        if (mRetrofit == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.addInterceptor(buildHttpLoggingInterceptor());

            setBuilder(builder);
            mOkHttpClient = builder.build();

            mRetrofit = new Retrofit.Builder()
                    .client(mOkHttpClient)
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
        return mRetrofit;
    }

    /**
     * 添加过滤器
     *
     * @return
     */
    public Interceptor buildHttpLoggingInterceptor() {
        return new HttpLoggingInterceptor(message -> Log.i(TAG, message));
    }

    /**
     * 构建 Retrofit 通用头
     *
     * @return OkHttpClient实例
     */
    public Interceptor buildGeneralHeader() {
        return chain -> chain.proceed(chain.request()
                .newBuilder()
                .build());
    }

    public <T> Observable.Transformer<T, T> applySchedulers() {
        return observable -> observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public void setBuilder(OkHttpClient.Builder builder) {

    }
}